<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\model\Site;
use app\common\model\SiteCategory;


class SiteAdmin extends AdminBase
{
    protected $category_model;
    protected $site_model;

    protected function _initialize()
    {
        parent::_initialize();

        $this->site_model = new Site();
        $this->category_model = new SiteCategory();
        $category_level_list = $this->category_model->catetree();
        $this->assign('category_level_list', $category_level_list);
    }

    public function index()
    {
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1;
        $perpage = isset($_REQUEST['perpage']) ? $_REQUEST['perpage'] : 10;
        $keyword = isset($_REQUEST['keyword']) ? trim($_REQUEST['keyword']) : '';
        $category_id = isset($_REQUEST['category_id']) ? trim($_REQUEST['category_id']) : 0;
        $status = isset($_REQUEST['status']) ? trim($_REQUEST['status']) : '';
        $famous = isset($_REQUEST['famous']) ? trim($_REQUEST['famous']) : '';
        $startdate = isset($_REQUEST['startdate']) ? trim($_REQUEST['startdate']) : '';
        $enddate = isset($_REQUEST['enddate']) ? trim($_REQUEST['enddate']) : '';
        $map = [];
        if ($category_id != '') {
            $map['f.category_id'] = $category_id;
        }

        if ($status != '') {
            $map['f.status'] = $status;
        }
        if ($famous != '') {
            $map['famous'] = $famous;
        }
        if ($keyword) {
            $map['title|f.keywords'] = ['like', "%{$keyword}%"];
        }
        if ($startdate) {
            $map['joined_at'] = ['egt', $startdate];
        }
        if ($enddate) {
            $map['joined_at'] = ['elt', $enddate . ' 23:59:59'];
        }

        $site_list = $this->site_model->alias('f')->join('site_category c', 'c.id=f.category_id', 'left')->order('f.id desc')->where($map)->field('f.*,c.name')->paginate($perpage);
        $this->assign(array('famous' => $famous, 'status' => $status, 'category_id' => $category_id, 'keyword' => $keyword, 'startdate' => $startdate, 'enddate' => $enddate, 'perpage' => $perpage));
        return $this->fetch('index', ['site_list' => $site_list]);
    }

    public function add()
    {
        return view();
    }

    public function save()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $domain = extractDomainFromUrl($data['link']);
            if (!$domain)
                return json(array('code' => 0, 'msg' => '链接地址不正确，需以http(s)://开头'));

            if (Site::get(['domain' => $domain]))
                return json(array('code' => 0, 'msg' => '已经添加过该网站'));

            unset($data['file']);
            unset($data['token']);
            $data['status'] = 1;
            $data['domain'] = $domain;
            $date = date('Y-m-d');
            $data['joined_at'] = $date;
            $data['updated_at'] = $date;
            $res = $this->site_model->allowField(true)->insert($data);
            if ($res) {
                return json(array('code' => 200, 'msg' => '添加成功'));
            } else {
                return json(array('code' => 0, 'msg' => '添加失败'));
            }
        } else {
            return json(array('code' => 0, 'msg' => '请求方式有误'));
        }
    }

    public function toggle($id, $status, $name)
    {
        if ($this->request->isGet()) {

            if ($this->site_model->where('id', $id)->update([$name => $status]) !== false) {
                return json(array('code' => 200, 'msg' => '更新成功'));
            } else {
                return json(array('code' => 0, 'msg' => '更新失败'));
            }
        }
    }

    /**
     * 编辑
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $site = $this->site_model->find($id);
        return $this->fetch('edit', ['site' => $site]);
    }

    /**
     * 更新
     * @throws \think\Exception
     */
    public function update()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $domain = extractDomainFromUrl($data['link']);
            if (!$domain) return json(array('code' => 0, 'msg' => '链接地址不正确，需以http(s)://开头'));
            $data['domain'] = $domain;
            $date = date('Y-m-d');
            $data['joined_at'] = $date;
            $data['updated_at'] = $date;
            $validate_result = $this->validate($data, 'Site');

            if ($validate_result !== true) {
                return json(array('code' => 0, 'msg' => $validate_result));
            } else {
                $res = $this->site_model->allowField(true)->save($data, ['id' => $data['id']]);
                if ($res) {
                    return json(array('code' => 200, 'msg' => '更新成功'));
                } else {
                    return json(array('code' => 0, 'msg' => '更新失败'));
                }
            }
        }
    }

    /**
     * 删除
     * @param $id
     * @throws \think\Exception
     */
    public function delete($id)
    {

        $info = $this->site_model->find($id);

        if ($this->site_model->destroy($id)) {

            return json(array('code' => 200, 'msg' => '删除成功'));
        } else {
            return json(array('code' => 0, 'msg' => '删除失败'));
        }
    }

    public function alldelete()
    {
        $params = input('post.');
        $ids = implode(',', $params['ids']);
        $result = $this->site_model->destroy($ids);
        if ($result) {
            return json(array('code' => 200, 'msg' => '删除成功'));
        } else {
            return json(array('code' => 0, 'msg' => '删除失败'));
        }
    }

    public function setHotSite()
    {
        $params = input('post.');
        $ids = implode(',', $params['ids']);
        $famous = $params['famous'];
        if (!is_numeric($famous) || ($famous > 2 || $famous < 0)) {
            return json(array('code' => 0, 'msg' => '只能输入0-2的数字'));
        }
        $result = $this->site_model->where(['id'=>['in',$ids]])->update(['famous'=>$params['famous']]);
        if ($result) {
            return json(array('code' => 200, 'msg' => '设置成功'));
        } else {
            return json(array('code' => 0, 'msg' => '设置失败'));
        }
    }

    //获取SEO信息
    public function getIcoPicScreen($url)
    {
        $screenshot = Site::getScreenshot($url);
        $code = 1;
        if (!$screenshot) {
            $code = 2;
            $ico = '';
        } else {
            $ico = Site::getIcoByUrl($url);
        }
        return json(array('code' => $code, 'data' => ['ico' => $ico, 'screenshot' => $screenshot]));
    }

    //获取getIcoPicScreen信息
    public function getSeoData($url)
    {
        $domain = extractDomainFromUrl($url);
        $res = Site::aizhanInfo($domain);
        if (!empty($res['data'])) {
            $code = 1;
            $seoData = $res['data'];
        } else {
            $code = 0;
            $seoData = [];
        }
        return json(array('code' => $code, 'data' => $seoData));
    }

    //设置点击数
    public function setClick()
    {
        $params = input('post.');
        foreach ($params['ids'] as $k => $v) {
            $info = $this->site_model->find($v);
        }

        $ids = implode(',', $params['ids']);
        $result = $this->site_model->destroy($ids);
        if ($result) {
            return json(array('code' => 200, 'msg' => '删除成功'));
        } else {
            return json(array('code' => 0, 'msg' => '删除失败'));
        }
    }
}
